<?php


namespace app\common\model\fp;

use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;
use think\Model;
use Throwable;

/**
 * 动态模型
 */
class PostMedia extends Model
{
    // 默认表名
    protected $name = 'fp_post_media';

    const TABLE_NUM = 10;

    /**
     * 如果表不存在，则创建新表
     *
     * @param string $tableName 要创建的表名
     * @return bool
     * @throws Throwable
     */
    public static function createTableIfNotExists(string $tableName): bool
    {
        $cacheKey = 'makeTable:'.$tableName;
        $check = Cache::get($cacheKey);
        if ($check) {
            return true;
        }

        // 检查表是否存在
        $exists = Db::query("SHOW TABLES LIKE  '{$tableName}'");

        if (!$exists) {
            $sql = <<<SQL
            CREATE TABLE `{$tableName}` (
                  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '媒体ID',
                  `post_id` bigint(20) unsigned NOT NULL COMMENT '动态ID',
                  `media_url` varchar(255) NOT NULL COMMENT '媒体文件链接',
                  `media_url_thumb` varchar(1000) NOT NULL DEFAULT '' COMMENT '缩略图',
                  `video_cover_url` varchar(255) NOT NULL DEFAULT '' COMMENT '视频封面',
                  `video_transcode_path` varchar(1000) NOT NULL DEFAULT '' COMMENT '视频转码',
                  `media_type` enum('image','video') NOT NULL COMMENT '媒体类型',
                  `create_time` int(11) NOT NULL COMMENT '创建时间',
                  PRIMARY KEY (`id`) USING BTREE,
                  KEY `media_type` (`media_type`),
                  KEY `post_id` (`post_id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='朋友圈-媒体表';
        SQL;

            try {
                Db::execute($sql);
            } catch (Throwable $e) {
                // 记录异常信息
                Log::channel('my')->error("Failed to create table {$tableName}: " . $e->getMessage());
                // 可以选择抛出异常或返回错误信息
                throw new \RuntimeException("Failed to create table: " . $e->getMessage(), 0, $e);
            }

        }

        Cache::set($cacheKey, 1);

        return true;
    }


    /**
     * 实例化表
     * @param $userId
     * @return PostMedia
     * @throws Throwable
     */
    public static function initModel($userId): static
    {
        $model = new static();

        $tableName = 'fp_post_media_' . ($userId % self::TABLE_NUM);
        $model->setName($tableName);

        $prefix = config('database.connections.mysql.prefix');
        self::createTableIfNotExists($prefix . $tableName);

        return $model;
    }

    public static function getDbTableName($userId, $hasPrefix = true): string
    {
        $tableName = 'fp_post_media_' . ($userId % self::TABLE_NUM);
        $prefix = '';
        if ($hasPrefix) {
            $prefix = config('database.connections.mysql.prefix');
        }
        return $prefix . $tableName;
    }
}